let sessionId = null;
async function obtenerUserId() {
const browserId = localStorage.getItem('browserId');
//console.log('[Frontend] browserId:', browserId);
if (!browserId) {
//console.log('[Frontend] No hay browserId, usando default');
return { user_id: null, user_name: 'Chelero-web-User' };
}
try {
const response = await fetch('/api/chatbot/obtener-usuario', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ browserId })
});
if (!response.ok) {
console.log('[Frontend] Error en response');
return { user_id: null, user_name: 'Chelero-web-User' };
}
const data = await response.json();
//console.log('[Frontend] Datos recibidos del endpoint:', data);
return data;
} catch (error) {
console.error('[Frontend] Error obteniendo usuario:', error);
return { user_id: null, user_name: 'Chelero-web-User' };
}
}
document.addEventListener('DOMContentLoaded', function() {
const chatbotToggle = document.getElementById('chatbot-toggle');
const chatbotClose = document.getElementById('chatbot-close');
const chatbotContainer = document.getElementById('chatbot-container');
const chatbotSend = document.getElementById('chatbot-send');
const chatbotInput = document.getElementById('chatbot-input');
const chatbotSpeech = document.getElementById('chatbot-speech');
const chatbotMessages = document.getElementById('chatbot-messages');
setTimeout(() => {
chatbotSpeech.classList.remove('hidden');
setTimeout(() => {
chatbotSpeech.classList.add('hidden');
}, 5000);
}, 3000);
chatbotToggle.addEventListener('click', function() {
chatbotContainer.classList.remove('chatbot-hidden');
chatbotSpeech.classList.add('hidden');
chatbotToggle.style.display = 'none';
chatbotInput.focus();
if (chatbotMessages.children.length === 0) {
cargarMensajes(); // Agregar esta línea
if (chatbotMessages.children.length === 0) {
setTimeout(() => {
agregarMensaje('bot', '¡Hola! 👋🍺 Soy Chelabot, tu asistente de Club Chelero. ¿En qué puedo ayudarte?');
}, 500);
}
}
});
chatbotClose.addEventListener('click', function() {
chatbotContainer.classList.add('chatbot-hidden');
chatbotToggle.style.display = 'block';
chatbotMessages.innerHTML = '';
});
chatbotSend.addEventListener('click', enviarMensaje);
chatbotInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
enviarMensaje();
}
});
});
async function enviarMensaje() {
const input = document.getElementById('chatbot-input');
const mensaje = input.value.trim();
if (!mensaje) return;
agregarMensaje('user', mensaje);
input.value = '';
agregarIndicadorEscribiendo();
try {
const userData = await obtenerUserId();
const response = await fetch('/api/chatbot/preguntar', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
pregunta: mensaje,
session_id: sessionId,
user_id: userData.user_id,
user_name: userData.user_name,
tel_usuario: userData.tel_usuario,
source_platform: 'club_chelero_web',
modelo_id: '68daa8536b668e23d40b5f99'
})
});
if (!response.ok) {
throw new Error('Error en la respuesta del servidor');
}
const data = await response.json();
if (data.session_id) {
sessionId = data.session_id;
}
quitarIndicadorEscribiendo();
agregarMensaje('bot', data.respuesta);
if (data.temas_relacionados && data.temas_relacionados.length > 0) {
agregarTemasRelacionados(data.temas_relacionados);
}
} catch (error) {
console.error('Error:', error);
quitarIndicadorEscribiendo();
agregarMensaje('bot', 'Lo siento, ocurrió un error. Por favor intenta de nuevo más tarde. 😕');
}
}
function agregarMensaje(tipo, contenido) {
const messagesDiv = document.getElementById('chatbot-messages');
const messageDiv = document.createElement('div');
messageDiv.className = `chatbot-message ${tipo === 'user' ? 'chatbot-message-user' : 'chatbot-message-bot'}`;
const htmlContenido = contenido
.replace(/\*\*(.*?)\*\*/g, '$1')
.replace(/\n/g, '
');
messageDiv.innerHTML = `